#include "CTimerFactory.h"

static CTimerFactory* s_instance = nullptr;
static mutex s_lock;
CTimerFactory* CTimerFactory::GetInstance()
{
	lock_guard<mutex> lock(s_lock);

	if (!s_instance)
	{
		s_instance = new CTimerFactory;
	}
	return s_instance;
}
void CTimerFactory::Release()
{
	lock_guard<mutex> lock(s_lock);

	delete s_instance;
	s_instance = nullptr;
}


CTimer* CTimerFactory::AllocateTimer()
{
	lock_guard<mutex> lock(s_lock);

	CTimer* pTimer = nullptr;

	auto it = m_mapTimers.begin();
	if (it == m_mapTimers.end())
	{
		pTimer = new CTimer;
	}
	else
	{
		pTimer = it->second;
		m_mapTimers.erase(it);
	}
	pTimer->Reset();
	return pTimer;
}

void CTimerFactory::Giveback(CTimer* &pTimer)
{
	lock_guard<mutex> lock(s_lock);

    quint64 id = (quint64)pTimer;

	m_mapTimers[id] = pTimer;

	pTimer = nullptr;
}
